package cn.chengpengper.seckill.activity.application.event.handler;

import cn.chengpengper.seckill.activity.application.cache.service.SeckillActivityCacheService;
import cn.chengpengper.seckill.activity.application.cache.service.SeckillActivityListCacheService;
import cn.chengpengper.seckill.activity.domain.event.SeckillActivityEvent;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.event.EventHandler;
import com.alibaba.cola.event.EventHandlerI;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.util.Objects;

/**
 * @author chengpeng.hu
 */
@Slf4j
@EventHandler
@RequiredArgsConstructor
@ConditionalOnProperty(name = "message.mq.type", havingValue = "cola")
public class SeckillActivityEventHandler implements EventHandlerI<Response, SeckillActivityEvent> {

    private final SeckillActivityCacheService seckillActivityCacheService;

    private final SeckillActivityListCacheService seckillActivityListCacheService;

    @Override
    public Response execute(SeckillActivityEvent seckillActivityEvent) {
        log.info("SeckillActivityEventHandler|接收到活动事件|{}", JSON.toJSON(seckillActivityEvent));
        if (Objects.isNull(seckillActivityEvent)) {
            log.info("SeckillActivityEventHandler|事件参数错误");
            return Response.buildSuccess();
        }
        seckillActivityCacheService.tryUpdateSeckillActivityCacheByLock(seckillActivityEvent.getId(), false);
        seckillActivityListCacheService.tryUpdateSeckillActivityCacheByLock(seckillActivityEvent.getStatus(), false);
        return Response.buildSuccess();
    }
}
